%%% This file is part of the Open HörTech Master Hearing Aid (openMHA)
%%% Copyright © 2021 HörTech gGmbH
%%% Copyright © 2021 2022 Hörzentrum Oldenburg gGmbH
%%%
%%% openMHA is free software: you can redistribute it and/or modify
%%% it under the terms of the GNU Affero General Public License as published by
%%% the Free Software Foundation, version 3 of the License.
%%%
%%% openMHA is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%%% GNU Affero General Public License, version 3 for more details.
%%%
%%% You should have received a copy of the GNU Affero General Public License, 
%%% version 3 along with openMHA.  If not, see <http://www.gnu.org/licenses/>.

% Latex header for doxygen 1.8.11
% adapted for openMHA
\documentclass[11pt,a4paper,twoside]{article}

% Packages required by doxygen
\usepackage{fixltx2e}
\usepackage{calc}
\usepackage{../openMHAdoxygen}
\setlength{\headheight}{13.6pt}
\usepackage[export]{adjustbox} % also loads graphicx
\usepackage{graphicx}
\usepackage[utf8]{inputenc}
\usepackage{makeidx}
\usepackage{multicol}
\usepackage{multirow}
\PassOptionsToPackage{warn}{textcomp}
\usepackage{textcomp}
\usepackage[nointegrals]{wasysym}
\usepackage[table]{xcolor}

% Font selection
\usepackage[T1]{fontenc}
\usepackage{helvet}
\usepackage{courier}
\usepackage{amssymb}
\usepackage{sectsty}
\usepackage{textcomp}
\renewcommand{\familydefault}{\sfdefault}
\allsectionsfont{%
  \fontseries{bc}\selectfont%
  \color{darkgray}%
}
\renewcommand{\DoxyLabelFont}{%
  \fontseries{bc}\selectfont%
  \color{darkgray}%
}
\newcommand{\+}{\discretionary{\mbox{\scriptsize$\hookleftarrow$}}{}{}}

% Headers & footers
\usepackage{fancyhdr}
\pagestyle{fancyplain}
\renewcommand{\sectionmark}[1]{%
  \markright{\thesection\ #1}%
}
\fancyhead[LE]{\fancyplain{}{\bfseries\thepage}}
\fancyhead[CE]{\fancyplain{}{}}
\fancyhead[RE]{\fancyplain{}{\bfseries\leftmark}}
\fancyhead[LO]{\fancyplain{}{\bfseries\rightmark}}
\fancyhead[CO]{\fancyplain{}{}}
\fancyhead[RO]{\fancyplain{}{\bfseries\thepage}}
\fancyfoot[LE]{\fancyplain{}{}}
\fancyfoot[CE]{\fancyplain{}{}}
\fancyfoot[RE]{\fancyplain{}{\bfseries\scriptsize \copyright{} 2005-2021 H\"orTech gGmbH, Oldenburg, \bfseries\scriptsize \copyright{} 2021-2022 H\"orzentrum Oldenburg gGmbH }}
\fancyfoot[LO]{\fancyplain{}{\bfseries\scriptsize \copyright{} 2005-2021 H\"orTech gGmbH, Oldenburg, \bfseries\scriptsize \copyright{} 2021-2022 H\"orzentrum Oldenburg gGmbH }}
\fancyfoot[CO]{\fancyplain{}{}}
\fancyfoot[RO]{\fancyplain{}{}}

% Indices & bibliography
\usepackage{natbib}
\usepackage{tocloft}
\setcounter{tocdepth}{2}
\setcounter{secnumdepth}{4}
\addtolength{\cftsubsecnumwidth}{5pt}
\usepackage{fancyvrb}


\RecustomVerbatimCommand{\VerbatimInput}{VerbatimInput}%
{fontsize=\footnotesize,
 %
 frame=lines,  % top and bottom rule only
 framesep=2em, % separation between frame and text
 rulecolor=\color{Gray},
 %
 label=\fbox{\color{Black}data.txt},
 labelposition=topline,
 %
 commandchars=\|\(\), % escape character and argument delimiters for
                      % commands within the verbatim
 commentchar=*        % comment character
}

\makeindex

% Custom commands
\newcommand{\clearemptydoublepage}{%
  \newpage{\pagestyle{empty}\cleardoublepage}%
}

\usepackage{caption}
\captionsetup{labelsep=space,justification=centering,font={bf},singlelinecheck=off,skip=4pt,position=top}

\setlength\parindent{0pt}
\usepackage{hyperref}
\usepackage[hang,flushmargin]{footmisc}
\usepackage[margin=1in]{geometry}
\usepackage{color}
\usepackage{subcaption}
\usepackage{fancyvrb} %Für Rahmen um Code Boxen
\usepackage{listings}

 \lstdefinestyle{customc}{
 commentstyle=\color{orange},
   columns = flexible
   basicstyle = \ttfamily,
   showstringspaces = false,
   numbers=left,
   numberstyle=\tiny,
   frame = single
 }

\lstset{style=customc}

\begin{document}
\MHAtitle{Matlab Coder integration}
\newpage
\MHAcopyright{}
\newpage
\tableofcontents
\newpage
\pagenumbering{arabic}
\section{Introduction}
\label{section:Introduction}

For many audiological researchers the tool of choice for prototyping new algorithms is \Matlab{}.
When the prototype reaches a certain stage of maturity there is oftentimes the desire to test
the new algorithm within the context of a quasi realistic real-time hearing aid processing and/or
under field conditions embedded in a mobile processing platform.

\mha{} offers the researcher a powerful and flexible toolset capable of real-time audio processing
even on limited hardware, but it is written in C++. Porting an advanced signal processing algorithm
from \Matlab{} code to C++ can be a hassle and sometimes poses insurmountable due to limited manpower
or institutional knowledge of C++. 


This document describes how to integrate user \Matlab{} code into \mha{}
as a plugin via translation to C/C++ by the \Matlab{} Coder.


\subsection*{Nomenclature}
\begin{itemize}
\item \textbf{user code} refers to the \Matlab{} code the user wants to integrate
  into \mha{} via \Matlab{} Coder,
\item \textbf{user function} means the entry point functions in the user code and
  their translated forms,
\item \textbf{generated code} refers to the C/C++ source code the
  Coder generates from this code,
\item \textbf{user library} refers to the shared library compiled
  from the generated code.
\item Text written like \texttt{this} refers to names of variables or structs in
  source code and \texttt{call()} refers to functions. \texttt{this.m} means
  file names.
\end{itemize}

\subsection*{Prerequisites}
In order to make use of this document the user needs a copy of \mha{}, either
in source code or binary form, a \Matlab{} Coder license and a general
understanding of the usage of \mha{}. In order to use the matlab\_wrapper plugin
the generated code needs to be compiled either from within the \Matlab{} Coder
or manually. See the \Matlab{} Coder documentation on how to integrate a compiler
into the Coder.
The user should have some idea on how to answer the following questions:
\begin{itemize}
\item What the purpose of a compiler?
\item What is the difference between source code and compiled code?
\item What is a plugin in the \mha{} context?
\item What is a \Matlab{} struct?
\end{itemize}
For more information consult the \mha{} application manual.

\subsection*{Document structure}
There are two ways to integrate the generated code into \mha{} as 
as plugin: The matlab\_wrapper plugin and the `native compilation'. The matlab\_wrapper
plugin is easier to use but less flexible. The plugin is provided the name of
the user library to the plugin. The plugin then loads the user library and calls the user functions at the appropriate times.
This approach relies on the user code following a prescribed form described in section~\ref{sec:wrapper plugin}.

The `native compilation' approach offers more flexibility but the user must be able to set up a development environment
able to compile \mha{} from source, and know some C++ in order to integrate the
generated code into the provided source code. This approach is described in section~\ref{sec:native compilation}.

\subsection*{Which approach to use?}
There is no hard and fast rule on which approach to use for a given algorithm. The
following guidelines can be used to figure out which approach probably fits best.

Usage of the matlab\_wrapper plugin is recommended if:
\begin{itemize}
\item There is little or no institutional knowledge of C++
\item The user code does hold no or only simple state, i.e. there is no or only
  simple data that needs to be stored from one audio block processing to the next.
\item No or little configuration at runtime is needed
\item The user code has a monolithic structure, i.e.\ it can be thought of as
  one big black box where the signal goes in and output comes out
\item Little or no interaction with the rest of \mha{} is desired
\end{itemize}
On the other hand the native compilation approach should be used if:
\begin{itemize}
\item Data sharing beyond the audio signal itself with \mha{} is needed
\item The algorithm structure itself is subject to change
\item The user code is modular and the modularity needs to be preserved
\item It is impossible to rewrite the user code to the prescribed structure for
  the wrapper plugin
\end{itemize}
Independent of the approach the integration will be easier if the code already fits the
structure described in~\ref{subsec:writing_code}. If it is known at the beginning
that an integration into \mha{} is desired it can be advantageous to write the user
code according to the described structure in the first place.

\section{The \Matlab{} Coder in a nutshell}
This section only introduces the most important terms needed to understand this
documentation. It can not replace the Matlab Coder documentation.
Please consult the official Matlab Coder manual for further information.

\subsection*{Introduction}
The Matlab Coder generates C/C++ code from \Matlab{} code. This code can then be
compiled using the \Matlab{} compiler or any other compiler. The generated code
can be integrated into \mha{} either in source code or in compiled form via the
matlab\_wrapper plugin. The matlab\_wrapper plugin can only accept compiled C code.

\subsection*{Entry-point functions}
An entry-point function is a top-level \Matlab{} function that gets compiled to
C/C++ code. Only functions marked as entry-point functions are guaranteed to be
generated as callable functions visible from the outside of the user code. The
matlab\_wrapper plugin expects some entry-point functions to be present, see
subsection~\ref{subsec:writing_code}.

\subsection*{Input types}
Because C is statically typed, all input and output types must be known at
compile time. Unlike in \Matlab{}, input and output types become part of the
function signature and can not be changed later, including array dimensions.
If a function needs to accept variable size arrays, they need to be wrapped
in a struct, done automatically at code generation.

The \Matlab{} Coder handles double, single, and half precision floating point
numbers, 8-, 16-, 32-, and 64-bit signed and unsigned integers, logicals
(booleans), characters and structs, cell arrays and strings. These can be either single values or
matrices. The size of a matrix is denoted by $\mathtt{\!X} \times \mathtt{\!Y}$, $\mathtt{\!X}$ denoting the number
of rows and $\mathtt{\!Y}$ the number of columns. $\mathtt{:\!X}$ means `up to X rows/columns' and $\mathtt{Inf}$
means an indeterminate size. The type of input argument can either be specified
manually or defined by example. See the \Matlab{} Coder documentation for
details.

\section{Usage of the matlab\_wrapper plugin}\label{sec:wrapper plugin}

The matlab\_wrapper plugin is the easiest but most restricted way to integrate
\Matlab{} code into \mha{}. To use it, the user compiles the user code into a
shared library. The matlab\_wrapper plugin then takes the library name without
suffix as configuration variable\\ \texttt{library\_name}. The plugin then automatically
resolves the entry-point functions and calls them during the appropriate
callback, passing signal dimensions and input signal to the user code. Because
the functions are resolved by name, the user code has to follow the form
described in~\ref{subsec:writing_code} for the matlab\_wrapper plugin to
properly resolve them.

If configuration at run time is desired, the \texttt{user\_config}
struct can be used (see section~\ref{subsec:writing_code} for details).
The plugin parses the entries of user configuration and creates an
\mha{} configuration variable for each entry. These variables can be
changed during processing without impeding real-time safety.

\subsection{Writing code targeting the matlab\_wrapper plugin}\label{subsec:writing_code}
\subsubsection{User code structure}\label{subsec:code_structure}
The user code and the plugin interface via four entry point functions:
\texttt{init()}, \texttt{prepare()}, \texttt{process()}, and \texttt{release()}, of which \texttt{process()} is mandatory.
These functions are automatically called by the wrapper plugin at construction, and during the \texttt{prepare()},
\texttt{process()} and \texttt{release()} callbacks respectively.
In order for the matlab\_wrapper plugin to properly resolve these functions, they must confirm to the prescribed interface,
i.e.\ their input and output parameters must be exactly as described in the following.\\

\texttt{init()} is called when the user library is loaded. It must follow the form:
\begin{lstlisting}[language=Matlab]
  function [user_config,state] = init(user_config,state)
\end{lstlisting}
\texttt{user\_config} is a \texttt{1xInf} array of structs containing the following members:
\begin{description}
\item[name] A 1xInf char array, the name of 
\item[value] An InfxInf doubles array
\end{description}
\texttt{state} has the same type as \texttt{user\_config}.
If user defined configuration variables are desired, \texttt{user\_config} must
be created within the \texttt{init()} function, e.g.:
\begin{lstlisting}[language=Matlab]
  function [user_config,state] = init(user_config,state)
  user_config =...
[struct('name','writeable', 'value',ones(1,1))];
  end
\end{lstlisting}
The size of \texttt{user\_config} may not be changed after the call to \texttt{init()}. If the values of the
elements of \texttt{user\_config} need to be changed depending on the signal dimensions,
this can be done during the prepare call, where \texttt{signal\_dimensions} and
\texttt{user\_config} are available.
The \texttt{state} variable is initialized in the same way and used to keep
state data in between calls to \texttt{process()}.
\begin{lstlisting}[language=Matlab]
  function [user_config,state] = init(user_config,state)
  state = [struct('name','rmslevel','value',ones(1,1))];
  end
\end{lstlisting}
\texttt{prepare()} is called when the prepare command is issued. All
initialization that depends on the form of the signal should be done here,
furthermore the properties of the input signal can be checked, i.e., in case the 
processing requires a fixed number of channels or a certain sampling rate is
required. If the processing changes any signal property, the
appropriate member of \texttt{signal\_dimensions} must be changed accordingly to
inform the \mha{} framework of the change.
\texttt{prepare()} takes two arguments:
  \begin{description}
  \item[signal\_dimensions] is a struct with information about the input signal.
    If the processing changes any of the following parameters,
    they must be changed in the prepare call accordingly:
    \begin{description}
    \item[channels] A uint32 containing the number of channels in the signal.
    \item[domain] A char containing either `W' for waveform domain or `S' for spectral domain. 
    \item[fragsize] A uint32 containing the fragment size.
    \item[wndlen] A uint32 containing the window length of the FFT if in spectral domain, zero otherwise
    \item[fftlen] A uint32 containing the Length of the FFT in in spectral domain, zero otherwise.
    \item[srate] A double containing the sampling frequency of the signal.
    \end{description}
  \item[user\_config] as above.
  \item[state] as above.
  \end{description}
  Example:
\begin{lstlisting}[language=Matlab]
  function [signal_dimensions, user_config, state]=...
           prepare(signal_dimensions, user_config,state )
  user_config(1).value(1,1)=2; % Assign a value to the
                               % first element of user_config

  % Store the rmslevel per channel 
  state(1).value=zeros(signal_dimensions.channels); 

  % Output contains only one channel
  signal_dimensions.channels=1; 
  end
\end{lstlisting}
  All signal processing has to happen in the \texttt{process\_xy()} function. `\texttt{xy}'  takes different values
depending on the input and output signal domains. Use `ww' for waveform to
waveform processing,  `ss' for spectrum to spectrum processing,  `ws' for waveform
to spectrum, and `sw' for spectrum to waveform processing. The function has the following signature:
\begin{lstlisting}[language=Matlab]
  function [s_out,user_config,state] = process_xy(s_in,...
                                            signal_dimensions,...
                                            user_config,state)
\end{lstlisting}
The parameters \texttt{signal\_dimensions}, \texttt{user\_config}, and
\texttt{state} are described above.
\texttt{wave\_in} is a \texttt{InfxInf} array of doubles or complex numbers in
the case of spectral processing.

The \texttt{release} function is used to do final cleanup if necessary.
It takes no parameters and returns nothing:
\begin{lstlisting}[language=Matlab]
  function release()
  ...
  end
\end{lstlisting}
\subsection{User configuration}
As mentioned before, user configuration must be initialized in the form of a
vector of structs in the \texttt{init()} function.
The elements of \texttt{user\_config} may be changed during processing,
but changes to \texttt{signal\_dimensions} are not allowed. 
For every element of \texttt{user\_config}, an \mha{} configuration variable
with the same name is created, allowing changes to the \texttt{user\_config} in
a real-time safe way.
A current limitation is that changes made to \texttt{user\_config} during \texttt{process()} are
lost on configuration change from the parser side, so the \texttt{state}
argument should be used to keep dynamic state like i.e.\ filter states.
\subsection{State keeping}
State keeping can be done in one of two ways. The quick option is to define the
stateful variable as \texttt{persistent} or \texttt{global}. This has the
downside that the variables are shared between all instances of the user
library, making it unsafe to load the user library more than once at a time.
The upside is that these variables may have any type and may change their size
at any time, although changing their size may not be real-time safe. \\
Alternatively, the \texttt{state} input/output variable may be used as shown above in section~\ref{subsec:code_structure}.
It has the same type as the \texttt{user\_config} variable and follows similar rules.
All elements of \texttt{state} must be initialized with \emph{name} and initial \emph{value}
in \texttt{init()}. The size of the element \texttt{value} may only be changed
during \texttt{init()} and \texttt{prepare()}. During \texttt{process()} only
the elements of value may be changed, but not its size. Changing the size during
\texttt{process()} is not real-time safe and leads to a crash. \mha{} parses the
contents of \texttt{state} and makes its elements available as monitor variables.
\subsection{Deployment}
\label{subsec:Deployment}
In order to get a ready to use user library, the \Matlab{} Coder needs to be
setup to use a compiler. Please refer to the \Matlab{} Coder documentation for
how to do this. If the user library is compiled using a different compiler than
\mha{} there may be compatibility problems. If possible, use the MinGW
compiler on Windows, the gcc compiler on Linux, and clang on macOS. If the \Matlab{} Coder
can not be setup to use a compatible compiler, the generated code may need to be
exported using the \texttt{packNGo} utility provided by the \Matlab{} Coder and
compiled manually. For compilation, the same setup as is used to compile \mha{}
can be used. See \texttt{COMPILATION.md} for details. \\
In any case the user library (usually a shared library with the file ending
\texttt{.so}, \texttt{.dylib}, or \texttt{.dll}) then needs to be copied to where
\mha{} looks for its plugins. By default these locations are
\begin{itemize}
\item \texttt{C:\textbackslash\textbackslash Program Files\textbackslash openMHA\textbackslash bin} (Windows)
\item \texttt{/usr/local/lib/openmha} (macOS)
\item \texttt{/usr/lib} (Linux)
\end{itemize}
\subsection{Example}
This section describes step-by-step how to go from the empty template code
in \\ \texttt{examples/24-matlab-wrapper-simple}
to a user library implementing a simple delay-and-sum algorithm, where the delay
and the gain are real-time configurable on a per-channel basis.
The finished code can be found in \texttt{examples/25-matlab-wrapper-advanced}.
\subsubsection*{Init}
Let's take a look at the contents of \texttt{init.m}. We know we want two
configuration variables:
The delay and the gain, so we need a vector of two structs:
\begin{lstlisting}[language=Matlab]
function [user_config, state] = init(user_config, state)
user_config =[struct('name','delay', 'value',ones(1,1)); ...
              struct('name','gain','value',ones(1,1))];
end
\end{lstlisting}
The first element of \texttt{user\_config} is named \texttt{delay}, the second one is named
\texttt{gain}. The actual value of the configuration variable is stored in the \texttt{value}
member. As we want one entry per channel but do not yet know the number of input
channels we just leave the initial value a $1\times1$ matrix of ones. Note that because of
the fixed interface, \texttt{value} must always be a matrix of doubles, even if,
as in this case, we only want to support integer values for the \texttt{delay} configuration
variable. \texttt{state} is not used in this example.
\subsubsection*{Prepare}
The next function of interest is \texttt{prepare()}, found in \texttt{prepare.m}:
\begin{lstlisting}[language=Matlab]
function [signal_dimensions, user_config, state] = ...
prepare(signal_dimensions, user_config, state)
if(signal_dimensions.domain~='W')
fprintf('This plugin can only process signals in the time domain. ...
         Got %s\n',signal_dimensions.domain);assert(false);
end

% Need one delay entry per input channel
user_config(1).value=zeros(signal_dimensions.channels,1);

% Need one gain entry per input channel
user_config(2).value=zeros(signal_dimensions.channels,1);

% Number of output channels is always one
signal_dimensions.channels=uint32(1);
end
\end{lstlisting}
The first thing we do in lines 3 to 5 is to check \texttt{signal\_dimensions} if the
input signal we get is really in the waveform domain and if not print an error
message and quit.
Next we need to resize the delay and the gain to the appropriate sizes. Both are
set to be vectors containing one element per channel. The number of channels is
available as \texttt{signal\_dimensions.channels}. As our user code changes the
dimensions of the signal we need to announce this fact to the \mha{} framework.
We do this by changing the \texttt{channels} member of \texttt{signal\_dimensions} to one.
Note that in line 15 we need to explicitly cast the value to the appropriate type lest we
get errors during code generation. Also observe that the change to \texttt{channels}
was the last thing we did, as we needed the original value before!
\subsubsection*{process\_ww, process\_ss, process\_sw and process\_ws}
In order to be able to use \texttt{make.m} for every combination of of input and
output signal domain with minimal changes, we introduce \texttt{process\_ww},
\texttt{process\_ss}, \texttt{process\_ws}, and \texttt{process\_sw}. These entry-point functions serve
as proxy for the real processing processing function and all contain the same
code forwarding the call to the `real' processing function:
\begin{lstlisting}[language=Matlab]
function [s_out,user_config,state] = process_ss(s_in,...
                               signal_dimensions,...
                               user_config,state)
% This function provides the entry point for spectrum to spectrum
% processing and forwards the actual processing to process(...)
% Do not touch unless you know what you are doing! 
% The actual processing should be done in process.m
[s_out,user_config]=process(s_in,signal_dimensions,user_config);
end
\end{lstlisting}
This allows us to keep the code invoking the \Matlab{} mostly the same. More on
that later. 
\subsubsection*{Process}
\begin{lstlisting}[language=Matlab]
function [wave_out,user_config,dummy] = ...
process(wave_in,signal_dimensions, user_config, dummy)

delay=user_config(1).value;
gain=user_config(2).value;

persistent state;
if(isempty(state))
    state=zeros(signal_dimensions.fragsize+uint32(max(delay(:))),...
                signal_dimensions.channels);
end

persistent read_idx;
if(isempty(read_idx))
    read_idx=uint32(zeros(signal_dimensions.channels));
end

persistent write_idx;
if(isempty(write_idx))
    write_idx=delay;
end

for fr=1:signal_dimensions.fragsize
    for ch=1:signal_dimensions.channels
        write_idx(ch)=mod(write_idx(ch),...
                          (signal_dimensions.fragsize+delay(ch)))+1;
        state(write_idx(ch),ch)=wave_in(fr,ch);
    end
end

wave_out=zeros(signal_dimensions.fragsize,1);
for fr=1:signal_dimensions.fragsize
    for ch=1:signal_dimensions.channels
        read_idx(ch)=mod(read_idx(ch),... 
                        (signal_dimensions.fragsize+delay(ch)))+1;
        wave_out(fr)=wave_out(fr)+...
                     state(read_idx(ch),ch)*10^(gain(ch)/10);
    end
end
end
\end{lstlisting}
In lines 4 and 5 we define shorthand notations for delay and gain. This makes it
easier to follow the code.
Next we define some helper variables. We implement
the delay line as a ringbuffer with the lag between read and write index
appropriately chosen for the delay. As we want to delay every channel
independently we need to keep state for every channel. The state vector
needs to be able to contain all incoming samples of a block in addition to the
delayed samples from the past. Because we need to keep the state in between
calls to process, we define the state matrix and the read and write indices as
persistent. Alternatively we could use entries in \texttt{state} to
store them, as used in example 28 (\texttt{examples/28-matlab-wrapper-spec2wave/}).
Next, we loop over the input signal to fill our state vector,
advancing the write pointer appropriately. In line 31 we initialize the output
signal to zero and then loop over the state vector, adding the delayed samples
from different channels together.
\subsubsection*{Release}
The last function we can fill is \texttt{release()}:
\begin{lstlisting}[language=Matlab]
function release()
end
\end{lstlisting}
We do not need to do any cleanup, so we leave it empty.
\subsubsection*{Deployment}
To generate the C code from our \Matlab{} code we can use \texttt{make.m}
unchanged. Let's take a look:
\begin{lstlisting}[language=Matlab]
function make(iodomain,varargin)
...
end
\end{lstlisting}
The \texttt{make()} function takes several arguments, of which the first,
\texttt{iodomain} is mandatory. \texttt{iodomain} determines the input and output
domains of the generated code. It is a string and must take one of the following
values:
\begin{description}
\item[ww] wave to wave 
\item[ss] spectrum to spectrum
\item[ws] spectrum to wave
\item[sw] wave to spectrum
\end{description}
The optional parameters are
\begin{description}
\item[outputName] (string) The name of the generated library
\item[packOutput] (logical) If the generated code should be packed in a
  self-contained zip file
\end{description}
In this example, we invoke the coder with
\begin{lstlisting}[language=Matlab]
make('ww','outputName','example_25','packOutput',true);
\end{lstlisting}
At the beginning we initialize the \texttt{coder} configuration object to some
sensible defaults:
\begin{lstlisting}[language=Matlab]
%% Create configuration object of class 'coder.CodeConfig'.
cfg = coder.config('dll','ecoder',false);
cfg.GenerateReport = true;
cfg.ReportPotentialDifferences = false;
cfg.SaturateOnIntegerOverflow = false;
cfg.FilePartitionMethod = 'SingleFile';
cfg.EnableOpenMP = false;
cfg.RuntimeChecks = true;
cfg.SupportNonFinite = false;
cfg.HardwareImplementation.ProdHWDeviceType = ...
                'Generic->32-bit x86 compatible';
cfg.HardwareImplementation.ProdLongLongMode = true;
cfg.HardwareImplementation.TargetLongLongMode = true;
\end{lstlisting}
We define the target device, enable run-time checks, etc.
A complete list can be found in the \Matlab{} Coder documentation. Changing the
settings should only be done after careful consideration and never without
reason. \\
The second section defines the types of the input arguments for \texttt{init()}:
\begin{lstlisting}[language=Matlab]
%% Define argument types for entry-point 'init'.
ARGS = cell(4,1);
ARGS{1} = cell(1,1);
ARGS_1_1 = struct;
ARGS_1_1.name = coder.typeof('X',[1 Inf],[0 1]);
ARGS_1_1.value = coder.typeof(0,[Inf Inf],[1 1]);
ARGS{1}{1} = coder.typeof(ARGS_1_1,[Inf  1],[1 0]);
ARGS{1}{1} = coder.cstructname(ARGS{1}{1},'user_config_t');
ARGS{1}{2} = ARGS{1}{1};
\end{lstlisting}
Changing any of these required customization of the matlab\_wrapper plugin. If
such customization seems necessary choosing the native compilation approach is
recommended. \\
The last section actually invokes the \Matlab{} coder:
\begin{lstlisting}[language=Matlab]
codegen('-config',cfg,...
    '-o',outputName,...
    'init','-args',ARGS{1},...
    'prepare','-args',ARGS{2},...
    process_name,'-args',ARGS{args_idx},...
    'release');
\end{lstlisting}
The \texttt{-config} argument takes the configuration object we constructed
earlier, \texttt{-o} takes the output file name, which can be passed as
argument, otherwise defaults to the name of the first entry point function.
The rest of the invocation defines the entry-point functions and their argument
types pairwise. \texttt{process\_name} and \texttt{args\_idx} are determined by
\texttt{iodomain}.
If the generated code needs to be compiled by hand, we need to
pass \texttt{packOutput} as \texttt{true} to execute the last block in \texttt{make.m}:
\begin{lstlisting}[language=Matlab]
%% Optionally package the code for deployment elsewhere
if(packOutput)
    buildInfo=load(['codegen/dll/' outputName '/buildInfo.mat']);
    packNGo(buildInfo.buildInfo,'fileName',[outputName '.zip']);
end
\end{lstlisting}
This makes the \texttt{packNGo} utility compress all source code needed to compile
the plugin into \texttt{outputname.zip}.
We then can move the contents of the resulting zip file into a separate
directory and compile them using Makefile provided in the example directory.
Note that this also enables us to use the \Matlab{} Coder on one machine and deploy
the generated code on another machine where the Coder is not available. \\
The makefile needed to compile the example is relatively simple as far as
makefiles go:
\begin{lstlisting}[language=make]
example_25.so: example_25.o example_25_emxAPI.o example_25_emxutil.o
    $(CC) -shared -o $@ $^
\end{lstlisting}
In the first line we define the target library we want to compile and its dependencies:
\texttt{example\_25.so} depends on \texttt{example\_25.o}, \texttt{example\_25\_emxAPI.o}, 
and \texttt{example\_25\_emxutil.o}. The Make program automatically provides the rule 
to how compile \texttt{.o} files from \texttt{.c} files.
Here the first file, \texttt{example\_25.c}, contains the actual
generated source code, \texttt{example\_25\_emxAPI.c} and
\texttt{example\_25\_emxutil.c} contain utility code handling the structures the
\Matlab{} coder generates to handle variable size matrices and similar
constructs. \\
This Makefile should be fairly universal and be usable for any system needing only 
small adjustments like e.g.\ the file suffix for shared libraries in and the actual 
name of the input and output files. If needed the compiler flags can be customized further.
See the documentation of your compiler for details. \\
If, on the other hand, the \Matlab{} Coder was set up to use a compiler that produces \mha{} compatible
output we can just move the resulting user library, usually a shared library with the file ending
\texttt{.so}, \texttt{.dylib}, or \texttt{.dll}, to the appropriate directory, start \mha{},
point the matlab\_wrapper plugin to the library and configure the user
algorithm, like shown in \texttt{example\_25.cfg}:
\begin{lstlisting}
nchannels_in = 2
fragsize=128
srate = 16000

iolib = MHAIOFile
io.in = example_25.wav
io.out = out.wav

mhalib = matlab_wrapper
mha.library_name=example_25
cmd=prepare
mha.delay=[50 100]
mha.gain=[-5 -5]
\end{lstlisting}
The first two sections are the usual setup routine for \mha{} where signal
parameters like the number of input channels, the fragment size and the sampling
rate are set up. We also tell \mha{} to use file-to-file processing for this
example with \texttt{example\_25.wav} as input and \texttt{out.wav} as output, respectively
Lines 9ff contain the actual configuration of the matlab\_wrapper plugin. We
first tell \mha{} to load the library named \texttt{example\_25}, leaving out the
file suffix. We then need to issue the \texttt{prepare} command because we reset
\texttt{delay} and \texttt{gain} to default values in our \texttt{prepare()}
function, overwritting all values we would assign before the prepare call.
Finally we set the delay to 50 and 100 samples respectively and the
gain to $-5\,\mathrm{dB}$ for both channels.

\section{Native compilation}\label{sec:native compilation}
If the code can not be rewritten to fit the wrapper plugin restrictions or when
only parts of the algorithm shall be implemented in \Matlab{} the `Native
compilation' approach can be used.
Here the user takes a the source code of a skeleton \mha{} plugin and writes
their own plugin, using the generated code only as building blocks,
finally compiling the plugin as any other self written \mha{} plugin.
This approach is much more flexible but requires more interaction
on part of the user. No step by step guide can be given, instead there are only
some guidelines and examples to observe. 
\subsection{User configuration}
The native compilation does not provide a ready made way to pass configuration parameters to the plugin.
One way is to define the configuration as input arguments to the matlab function.
The user then has to manually add MHAParser::* configuration variables and translate them to appropriate types and
pass them to the generated code when calling the signal processing functions.
Please the \texttt{examples/23-matlab-coder} for a beginner's example. This
example can be adjusted for the end user's needs.
\end{document}
%%% Local Variables:
%%% mode: latex
%%% TeX-master: "openMHA_matlab_coder_integration"
%%% indent-tabs-mode: nil
%%% coding: utf-8-unix
%%% End:
